<template>
	<div class="cr-body-content">
		<flexbox class="content-header">
			<el-input 
				v-model="searchContent" 
				size="mini" 
				class="search-container" 
				:placeholder="placeholder">
				<el-button 
					slot="append" 
					icon="el-icon-search" 
					@click.native="searchInput" />
			</el-input>
		</flexbox>
		<!-- 表格 -->
		<el-table
			ref="relativetable"
			v-loading="loading"
			:data="list"
			:height="350"
			stripe
			border
			highlight-current-row
			style="width: 100%"
			@selection-change="handleSelectionChange">
			<!-- 选框 -->
			<el-table-column
				v-if="fieldList.length > 0"
				show-overflow-tooltip
				type="selection"
				align="center"
				width="55"/>
			<!-- 字段 -->
			<el-table-column
				v-if="fieldList.length > 0"
				v-for="(item, index) in fieldList"
				:key="index"
				:prop="item.prop"
				:label="item.label"
				:width="item.width"
				:formatter="fieldFormatter">
				<template
				  slot="header"
				  slot-scope="scope">
				  <div class="table-head-name">{{ scope.column.label }}</div>
				</template>
			</el-table-column>
		</el-table>
		
		<!-- 分页操作 -->
		<div class="table-footer">
			<el-button
				:disabled="currentPage <= 1"
				size="mini"
				@click.native="changePage('up')">上一页</el-button>
			<el-button
				:disabled="currentPage >= totalPage"
				@click.native="changePage('down')"
				size="mini">下一页</el-button>
		</div>
	</div>
</template>
<script type="text/javascript">
	// API
	import { filedGetField } from '@/api/setting/setting'
	import { crmCustomerNopool } from '@/api/customer/customer'
	import moment from 'moment'
	import {
		getDateFromTimestamp,
		moneyFormat
	} from '@/utils'
	export default {
		name: 'CrmRelativeTable', // 相关模块CRMCell

		props: {
			show: {
				type: Boolean,
				default: false
			},
			actiontype: {
				type: [String,Number],
				default: ''
			},
			/** 多选框 只能选一个 */
			radio: {
				type: Boolean,
				default: true
			},
			/** 没有值就是全部类型 有值就是当个类型 */
			crmType: {
				type: String,
				default: ''
			},
			/** 已选信息 */
			selectedData: {
				type: Object,
				default: () => {
					return {}
				}
			},
			// id
			id: {
				type: [String,Number],
				default: ''
			},
		},
		data() {
			return {
				loading: false, // 加载进度
				searchContent: '', // 输入内容
				list: [], // 表数据
				currentPage: 1, // 当前页数
				totalPage: 1, // 总页数
				
				fieldList: [], // 表头数据
				/** 格式化规则 */
				formatterRules: {},
				
				otherItems: [],
				selectedItem: [], // 勾选的数据 点击确定 传递给父组件
			}
		},

		// 监听
		watch: {
			id: function(newValue, oldValue) {
				 // console.log(newValue);
				if (newValue) {
					this.fieldList = []
					this.getFieldList()
				}
			},
			crmType: function(newValue, oldValue) {
				if (newValue != oldValue) {
					this.fieldList = []
					this.getFieldList()
				}
			},
			show: {
				handler(val) {
					// 第一次点击打开弹窗的时候为true
					if (val && this.fieldList.length == 0) {
						this.getFieldList()
					}
				},
				deep: true,
				immediate: true
			},
			// 选择
			selectedData: function() {
				this.checkItemsWithSelectedData()
			}
		},
		computed: {
			placeholder() {
				if (this.crmType == 'customer') {
					return '请输入客户名称'
				} else{
					
				}
				
			}
		},
		methods: {
			// 进行搜索操作
			searchInput() {
				this.currentPage = 1
				this.getList()
			},
			
			// 当选择项发生变化时会触发该事件
			handleSelectionChange(val) {
				if (this.radio) {
					val.forEach((row, index) => {
						if (index === val.length - 1) return
						this.$refs.relativetable.toggleRowSelection(row, false)
					})
					if (val.length === 0) {
						this.selectedItem = []
					} else {
						this.selectedItem = val.length === 1 ? val : [val[val.length - 1]]
					}
				} else {
					this.selectedItem = this.otherItems.concat(val)
				}
				this.$emit('changeCheckout', {
					data: this.selectedItem,
					type: this.crmType
				})
			},
			
			// 上一页或下一页
			changePage(type) {
				if (type == 'up') {
					this.currentPage = this.currentPage - 1
				} else if (type == 'down') {
					this.currentPage = this.currentPage + 1
				}
				if (this.currentPage <= this.totalPage && this.currentPage >= 1) {
					this.getList()
				}
			},
			
			/** 获取字段 */
			getFieldList() {
				if (this.fieldList.length == 0) {
					let crmType
					crmType = this.crmType
					
					var params = {
						types: "crm_" + crmType,
						module: 'crm',
						action:'index'
					}
					if(this.actiontype){
						params.actiontype = this.actiontype
					}
					
					
					params.controller = this.crmType
					filedGetField(params)
						.then(res => {
							for (let index = 0; index < res.data.length; index++) {
								const element = res.data[index]
								/** 获取需要格式化的字段 和格式化的规则 */
								if (element.form_type === 'date') {
									this.formatterRules[element.field] = {
										formatter: function fieldFormatter(time) {
											if (time == '0000-00-00') {
												time = ''
											}
											if (time) {
												return moment(getDateFromTimestamp(time)).format(
													'YYYY-MM-DD'
												)
											}
											
											
										}
									}
								} else if (element.form_type === 'datetime') {
									this.formatterRules[element.field] = {
										formatter: function fieldFormatter(time) {
											if (time == 0 || !time) {
												return ''
											}
											return moment(getDateFromTimestamp(time)).format(
												'YYYY-MM-DD HH:mm:ss'
											)
										}
									}
								} else if (element.form_type === 'user' || element.form_type === 'user-multiple') {
									this.formatterRules[element.field] = {
										type: 'crm',
										formatter: function fieldFormatter(info) {
											if (info) {
												var content = ''
												for (let index = 0; index < info.length; index++) {
													const element = info[index]
													content = content + element.username + (index === (info
														.length - 1) ? '' : ',')
												}
												return content
											}
											return ''
										}
									}
								} else if (element.form_type === 'float') {
									this.formatterRules[element.field] = {
										type: 'floatnumber',
										formatter: function fieldFormatter(info) {
											return moneyFormat(info)
										}
									}
								} else if (element.form_type === 'select-multiple') {
									this.formatterRules[element.field] = {
										type: 'array',
										formatter: function fieldFormatter(info) {
											return info
										}
									}
								}
			
								var width = 0
								if (!element.width) {
									if (element.form_type == 'datetime') {
										width = 170
									} else if (element.form_type == 'textarea') {
										width = 350
									} else {
										width = 115
									}
								} else {
									width = element.width
								}
			
								this.fieldList.push({
									prop: element.field,
									label: element.name,
									width: width
								})
							}
							// 获取好字段开始请求数据
							this.getList()
						})
						.catch(() => {
							this.loading = false
						})
				} else {
					// 获取好字段开始请求数据
					this.getList()
				}
			},
			
			/** 格式化字段 */
			fieldFormatter(row, column) {
				// 如果需要格式化
				var aRules = this.formatterRules[column.property]
				if (aRules) {
					if (aRules.type === 'crm') {
						if (column.property) {
							// return aRules.formatter(row[column.property]) || '--'
							return aRules.formatter(row[column.property + '_info']) || '--'
						} else {
							return ''
						}
					} else {
						return aRules.formatter(row[column.property]) || '--'
					}
				}
				return row[column.property] || '--'
			},
			
			/** 获取列表数据 */
			getList() {
				this.loading = true
				var crmIndexRequest = this.getIndexRequest()
				var params = {
					page: this.currentPage,
					limit: 15,
					search_v: this.searchContent
				}
				if(this.id){
					params.id = this.id
				}
				crmIndexRequest(params).then(res => {
					/**
					 *  如果已选择的有数据
					 */
					if (this.selectedData[this.crmType]) {
						this.checkItemsWithSelectedData(res.data.list)
					} 
					// else {
					// 	this.list = res.data.list.map(element => {
					// 		element.show = false
					// 		return element
					// 	})
					// }
					this.list = res.data.list.map(element => {
						element.show = false
						return element
					})
					this.totalPage = Math.ceil(res.data.count / 15)
					this.$refs['relativetable'].doLayout()
					this.loading = false
				}).catch(() => {
					this.loading = false
				})
			},
			
			/** 获取列表请求 */
			getIndexRequest() {
				if(this.crmType === 'customer'){
					return crmCustomerNopool
				}
			},
			
			// 标记选择数据
			checkItemsWithSelectedData() {
				const selectedArray = this.selectedData[this.crmType].map(item => {
					item.has = false
					return item
				})
			
				const selectedRows = []
				this.otherItems = []
			
				this.list.forEach((item, index) => {
					selectedArray.forEach((selectedItem, selectedIndex) => {
						let crmType = this.crmType == 'cooperationlawyer' ? 'lawyer' : this.crmType
						if (
							item[crmType + '_id'] == selectedItem[crmType + '_id']
						) {
							selectedItem.has = true
							selectedRows.push(item)
						}
					})
				})
			
				selectedArray.forEach((selectedItem, selectedIndex) => {
					if (!selectedItem.has) {
						this.otherItems.push(selectedItem)
					}
				})
			
				this.$nextTick(() => {
					this.$refs.relativetable.clearSelection()
					selectedRows.forEach(row => {
						this.$refs.relativetable.toggleRowSelection(row, true)
					})
				})
			},
			
			clearAll() {
				this.$refs.relativetable.clearSelection()
			},
		}
	}
</script>

<style lang="scss" scoped>
	.cr-body-content {
		position: relative;
		background-color: white;
		border-bottom: 1px solid #eee
	}

	.content-header {
		position: relative;
		padding: 10px 20px;

		.search-container {
			margin: 0 20px 0 0;
			width: 250px;
		}

		.create-button {
			position: absolute;
			right: 10px;
			top: 15px;
		}
	}

	//表尾 上一页按钮
	.table-footer {
		padding: 8px 20px;
	}

	.el-table /deep/ thead th {
		font-weight: 400;
		font-size: 12px;
	}

	.el-table /deep/ tbody tr td {
		font-size: 12px;
	}

	.el-table /deep/ thead .el-checkbox {
		display: none;
	}
</style>
